//
//  QXUser.m
//  QXBlog
//
//  Created by QinXin on 15/7/5.
//  Copyright © 2015年 labi3285_Lab. All rights reserved.
//

#import "QXUser.h"
#import <objc/runtime.h>
#import "NSArray+Log.h"

#define k_shared_user_path @"/Users/labi3285/Desktop/QXBlog/user.data"

@implementation QXUser

+ (instancetype)sharedUser {
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [self unAchivedSharedData];
    });
    return instance;
}

- (void)achiveToSharedPath {
    [NSKeyedArchiver archiveRootObject:self toFile:k_shared_user_path];
}

+ (instancetype)unAchivedSharedData {
    return [NSKeyedUnarchiver unarchiveObjectWithFile:k_shared_user_path];
}

/// 构造方法
- (instancetype)initWithDic:(NSDictionary *)dic {
    if (self = [super init]) {
        
        // 首先检测每个key都能找得到
        for (NSString *key in dic) {
            if ([[QXUser properties] containsObject:key]) {
                [self setValue:dic[key] forKey:key];
            }
        }
    }
    return self;
}

/// 快速构造方法
+ (instancetype)userWithDic:(NSDictionary *)dic {
    return [[self alloc] initWithDic:dic];
}

/// 描述，用于调试
- (NSString *)description {
    NSDictionary *dic = [self dictionaryWithValuesForKeys:[QXUser properties]];
    return [NSString stringWithFormat:@"QXUser: %@", dic];
}

/// 动态取得所有属性（固定写法）
+ (NSArray *)properties {
    unsigned int propertyCount = 0;
    objc_property_t *propertyList = class_copyPropertyList([self class], &propertyCount);
    NSMutableArray *marr = [NSMutableArray arrayWithCapacity:propertyCount];
    for (int i = 0; i < propertyCount; i++) {
        objc_property_t property = propertyList[i];
        const char *cName = property_getName(property);
        NSString *ocName = [NSString stringWithUTF8String:cName];
        [marr addObject:ocName];
    }
    free(propertyList);
    return marr.copy;
}

#pragma mark - NSCoding
- (nullable instancetype)initWithCoder:(nonnull NSCoder *)aDecoder {
    if (self = [super init]) {
        for (NSString *key in [QXUser properties]) {
            [self setValue:[aDecoder decodeObjectForKey:key] forKey:key];
        }
    }
    return self;
}
- (void)encodeWithCoder:(nonnull NSCoder *)aCoder {
    for (NSString *key in [QXUser properties]) {
        [aCoder encodeObject:[self valueForKey:key] forKey:key];
    }
}

@end